
nums = [-2, -1, -1, 1, 1, 2, 2], target = 0

var fourSum = function (nums, target) {
    let res = []
    nums.sort((a, b) => (a - b))
    let len = nums.length
    for (let i = 0; i < len - 3; i++) {
        if (i > 0 && nums[i] === nums[i - 1]) continue;
        for (let j = i + 1; j < len - 2; j++) {
            if (j > i + 1 && nums[j] === nums[j - 1]) continue;
            let left = j + 1
            let right = len - 1
            while (left < right) {
                const value = nums[left] + nums[right] + nums[i] + nums[j];
                if (value === target) {
                    res.push([nums[i], nums[j], nums[left], nums[right]])
                    while (left < right && nums[right] === nums[right - 1]) right--
                    while (left < right && nums[left] === nums[left + 1]) left++;
                    left++
                    right--
                }
                else if (value > target) right--
                else if (value < target) left++
            }
        }
    }
    return res
};
console.log(fourSum(nums, target));
